$package('wstuo.rules');
$import('wstuo.rules.ruleCM');
$import('wstuo.rules.ruleMain');
/**
 * @author WSTUO
 * @constructor WSTO
 * @description 新增业务规则主函数.
 
 */
wstuo.rules.addRule = function() {

	this.i = 0;
	this.j = 0;
	this.loadshowRulesGrid=false;
	return {

		/**
		 * @description 加载规则集属性列表.
		 */
		ruleTermSet : function() {
			$("#addRule_team").html('');
			$("#addRule_matical").html('');
			// 调用加载规则条件集
			$(wstuo.rules.ruleCM.loadConditionHTMLs()).appendTo("#addRule_team");
			// 加载运算符
			$(wstuo.rules.ruleCM.loadConditionMathematicalOperationHTML())
					.appendTo("#addRule_matical");
		},

		/**
		 * @description 显示属性标题.
		 */
		add_switchTitle : function() {

			return $("#addRule_team").find("option:selected").text() + " "
					+ $("#addRule_matical").find("option:selected").text();
		},
		/**
		 * @description 规则条件匹配
		 */
		add_switchOrAnd : function() {
			var andOr = "<option value='or'>or</option><option value='and'>and</option>";

			if ($("#add_rule_and").attr("checked") == true) {
				andOr = "<option value='and'>and</option><option value='or'>or</option>";
			}
			return andOr;
		},
		/**
		 * @description 显示属性值.
		 */
		add_switchValue : function() {

			return wstuo.rules.ruleCM.getRuleTitle('#addRule_team',
					'#addRule_propertyValue', '#addRule_namePut');
		},

		/**
		 * @description 加载下拉列表项.
		 */
		setPVHTML : function() {

			var flag = $('#addRule_team').val();

			wstuo.rules.ruleCM.createRuleEvent('#addRule_content', flag,
					'#addRule_propertyValueDIV', 'addRule_namePut',
					'addRule_propertyValue', '');

		},

		/**
		 * @description 操作符
		 */
		setTerm : function() {

			wstuo.rules.ruleCM.setMathematicalOperation('#addRule_team',
					'#addRule_matical');
		},

		/**
		 * @description 提交新增.
		 */
		saveRule: function() {

			var _rulePackageNo = $('#Proce_rulePackageNo').val();

			if ((_rulePackageNo != null && _rulePackageNo != '') || _flag != "requestProce") {
				
				var actionsNames = $('#addRule_content form:eq(2) input[name="rule_actions_propertyName"]');
		
				if (actionsNames.length > 0) {
					wstuo.rules.addRule.existRuleName();
				} else {
					msgAlert(i18n.msg_msg_vaildateRulesAndAction, 'info');
				}
			} else {
				msgAlert(i18n.rule_requestProcess_package_tip, 'info');
			}
		},

		/**
		 * @description 提交新增.
		 */
		saveRuleMethod : function() {
			wstuo.rules.ruleCM.saveRuleCommon('#addRule_content', 'save',
					'#add_rule_and', _flag);
		},
		/**
		 * 验证规则名称是否存在
		 */
		existRuleName : function() {
			var ruleName = $("#addRule_Name").val();
			$.post('callBusinessRule!existRuleName.action', 'ruleName='
					+ ruleName + "&rulePackageNo=" + _rulePackageNo, function(
					data) {
				if (data) {
					msgAlert(i18n.msg_ruleName_exist, 'info');
				} else {
					wstuo.rules.addRule.saveRuleMethod();
				}
			});
		},
		/**
		 * 获取全部的id
		 */
		add_forValues : function() {
			var arr = new Array();
			var propertyValueid = $('#addRule_propertyValueid').val();
			var propertyValue = $('#addRule_propertyValue').val();
			var addPropertyID = $('#addRule_team').val();

			var arrayValue = "";

			if (propertyValueid != undefined){
				arr = propertyValueid.split(",");
			}else{
				arr = propertyValue.split(",");
			}
			var lan = arr.length;
			for ( var i = 0; i < lan; i++) {
				arrayValue += addPropertyID + arr[i] + ",";
			}
			return arrayValue;
		},

		/**
		 * @description 添加规则集.
		 */
		addToRuleList : function() {
			var exitTag = "0";
			var propertyName = $('#addRule_team').val() + ' '
					+ $('#addRule_matical').val();
			var propertyValue = $('#addRule_propertyValue').val();

			var propertyValueid = $('#addRule_propertyValueid').val();
			var addPropertyID = $('#addRule_team').val();

			if ($("#add_rule_and").attr("checked")) {
				$(
					"#addRule_constraintsTable input:hidden[name='rule_condition_constraints_propertyName']")
					.each(
							function(i, e) {

								if (propertyName == 'organizationNo =='
										&& propertyName == $(this).val()) {
									exitTag = "1";
								}
							});
			}

			var arr = $("." + addPropertyID);
			var arrValue = "";
			for ( var _int = 0; _int < arr.size(); _int++) {
				arrValue += $("." + addPropertyID + ":eq(" + _int + ")").val();
			}
			var array1 = new Array();
			var array2 = new Array();
			array1 = arrValue.split(",");
			var forValues = wstuo.rules.addRule.add_forValues();

			if (forValues.length > 1){
				forValues = forValues.substring(0, forValues.length - 1);
			}
			array2 = forValues.split(",");

			for ( var a = 0; a < array1.length; a++) {
				for ( var b = 0; b < array2.length; b++) {
					if (array1[a] === array2[b]) {
						msgAlert(i18n['label_requireHave'], 'info');
						return false;
					}
				}
			}

			if (propertyValue != '') {

				var key = $('#addRule_matical').val();

				if (key == "matches") {
					propertyValue = ".*" + propertyValue + ".*";
				}

				if (key == "matches start") {
					propertyValue = propertyValue + ".*";
				}

				if (key == "matches end") {
					propertyValue = ".*" + propertyValue;
				}
				if (key == "in") {
					propertyValue = propertyValueid;

					if (propertyValue == undefined)
						propertyValue = $('#addRule_propertyValue').val();
				}
				if (key == "notIn") {
					propertyValue = propertyValueid;

					if (propertyValue == undefined)
						propertyValue = $('#addRule_propertyValue').val();
				}
				if (addPropertyID == "weekNo") {
					propertyValue = wstuo.rules.ruleCM
							.convert_string(propertyValue);
				}
				if (exitTag == "0") {
					i++;

					var trHTML = wstuo.rules.ruleCM.replaceRuleStr(i,//
							wstuo.rules.addRule.add_switchTitle(),// 条件名称
					'',// 规则ID
					wstuo.rules.ruleCM.switchDataType('#addRule_team'),// 条件类型
					propertyName,// 属性名
					wstuo.rules.addRule.add_switchValue(),// 条件操作符
					wstuo.rules.addRule.add_switchValue(), propertyValue,// 条件值
					wstuo.rules.addRule.add_switchOrAnd(),// 连接方式
					addPropertyID,// 条件属性
					wstuo.rules.addRule.add_forValues(),// 条件值
					"addRule"// 添加或编辑

					);
					$("#addRule_constraintsTable tbody").append(trHTML);

					$('#addRule_propertyValue').val('');
					$('#addRule_namePut').val('');
					$('#addRule_propertyValue').val('');
				} else {
					msgAlert(i18n['msg_rule_ruleOrgAndHave'], 'info');
				}
			} else {

				msgAlert(i18n['msg_rule_ruleActionCanNotBeNull'], 'info');
			}
		},

		/**
		 * @description 执行动作.
		 */
		executeAction : function() {

			$(wstuo.rules.ruleCM.loadActionHTML()).appendTo(
					"#addRule_executeAction");
		},

		/**
		 * @description 显示效果.
		 */
		add_switchAction : function() {

			return $("#addRule_executeAction").find("option:selected").text();

		},

		/**
		 * 获取相关动作的标题以显示到列表.
		 */
		add_switchGavenValue : function() {

			return wstuo.rules.ruleCM.getRuleTitle('#addRule_executeAction',
					'#givenValue', '#givenValue_Panel');
		},

		/**
		 * 创建填写动作HTML控件.
		 */
		addRule_setExHTML : function() {

			var flag = $('#addRule_executeAction').val();
			wstuo.rules.ruleCM.createRuleEvent('#addRule_content', flag,
					'#givenValueDIV', 'givenValue_Panel', 'givenValue',
					'wstuo.rules.addRule.addRule_selectServiceOrg()');
		},

		/**
		 * @description 调用方法打开选择服务机构窗口.
		 */
		addRule_selectServiceOrg : function() {

			wstuo.rules.ruleCM.selectServiceOrg(
					'#index_selectServiceORG_window_tree',
					'#index_selectServiceORG_window', '#givenValue',
					'#givenValue_Panel');
		},

		/**
		 * @description 将条件添加到动作列表.
		 */
		addToActionList : function() {

			var propertyName = $('#addRule_executeAction').val();
			var givenValue = $('#givenValue').val();

			var exitTag = "0";

			$(
					"#addRule_actionTable input:hidden[name='rule_actions_propertyName']")
					.each(function(i, e) {

						if (propertyName == $(this).val()) {
							exitTag = "1";
						}
					});

			var valueTag = $('#givenValue').val();

			if (exitTag == "0" && valueTag != '') {

				j++;

				var trHTML = wstuo.rules.ruleCM.replaceActionStr(j,
						wstuo.rules.addRule.add_switchAction(),
						wstuo.rules.ruleCM.switchDataType('#addRule_executeAction'),
						propertyName,
						wstuo.rules.addRule.add_switchGavenValue(),
						wstuo.rules.addRule.add_switchGavenValue(), givenValue,
						"#action" + j);
				$("#addRule_actionTable").append(trHTML);
				$('#givenValue').val('');
				$('#givenValue_Panel').val('');
			} else {
				if (valueTag == '') {
					msgAlert(i18n['label_rule_actionCanNotBeNull'], 'info');
				} else {
					msgAlert(i18n['label_rule_actionExist'], 'info');
				}
			}
		},
		/**
		 * @description 添加多个规则
		 */
		addMultitermRule : function() {
			$('#rightop option').attr("selected", true);
			var strId = $('#rightop').val();
			var strText = "";
			$('#rightop').each(function() {
				$(this).children("option").each(function() {
					strText += $(this).text() + ",";

				})
			});

			var lan = strText.length;
			strText = strText.substring(0, lan - 1);

			$('#addRule_propertyValueid').val(strId);
			$('#addRule_propertyValue').val(strText);
			$('#editRule_propertyValue').val(strText);
			$('#multitermSLA').dialog('close');
		},
		/**
		 * @description 数据标识格式化
		 * @param cell 列显示值
		 * @param event 事件
		 * @param data 行数据
		 */
		dataFlagFormatter : function(cell, event, data) {

			if (data.dataFlag == 1) {
				return "<span style='color:#ff0000'>[System]</span>&nbsp;"
						+ data.ruleName;
			} else {
				return data.ruleName;
			}
		},
		/**
		 * @description 确认按键格式
		 * @param cell 列显示值
		 * @param event 事件
		 * @param data 行数据
		 */
		confirmCheckFormatter : function(cell, event, data) {
			return '<div style="padding:0px">'
					+ '<a href="javascript:wstuo.rules.addRule.confirmCheck(\''
					+ data.rulePackageNo + '\',\''
					+ data.flagName + '\',\''
					+ data.packageName.replace("com.drools.drl.", "")
					+ '\')" title="' + i18n.check + '">'
					+ '<i class="glyphicon glyphicon-ok"></i></a>' + '</div>';
		},
		/**
		 * @description 确认选择
		 * @param rulePackageNo 规则包ID
		 * @param packageName 规则包名称
		 */
		confirmCheck : function(rulePackageNo,flagName, packageName) {
			$('#Proce_rulePackageNo').val(rulePackageNo);
			$('#Proce_rulePackageName').val(packageName);
			if(flagName=="saveRequest"){
				wstuo.rules.ruleCM.loadType("requestFit");
			}else if(flagName=="requestProce"){
				wstuo.rules.ruleCM.loadType("requestProce");
			}else if(flagName=="saveChange"){
				wstuo.rules.ruleCM.loadType("changeApproval");
			}else if(flagName=="changeProce"){
				wstuo.rules.ruleCM.loadType("changeProce");
			}
			if($('#Proce_ruleFlagName').val()!=flagName){
				$('#Proce_ruleFlagName').val(flagName);
				$('#addRule_executeAction').html('');
				wstuo.rules.addRule.executeAction();
			}
			wstuo.rules.addRule.addRule_setExHTML();
			$('#selectRuleMatchRuleSelectWin').dialog('close');
		},
		/**
		 * @description 清除指定ID值
		 * @param rulePackageNo 规则包ID
		 * @param ruleName 规则名称
		 */
		cleanIdValue : function(rulePackageNo, ruleName) {
			msgConfirm(i18n['msg_msg'],'<br/>'+i18n['lable_Action_set_list_will_be_empty'],function(){
				$('#Proce_rulePackageNo').val('');
				$('#Proce_rulePackageName').val('');
				$('#Proce_ruleFlagName').val('');
				$('#addRule_executeAction').html('<option value="">'+i18n["rule_requestProcess_package_tip"]+'</option>');
				for(var ids=0;ids<=j;ids++){
					basics.tableOpt.trDelRule('#action'+ids)
				}
				$('#givenValueDIV').html("<input class='form-control' style='width:170px;' />");
			});
		},
		isToFlagName:function(cellvalue, options, rowObject){
			  if(cellvalue=="saveRequest"){
				  return "<span style='color:#ff0000'>[System]</span>&nbsp;"+i18n["lable_Added_triggered_request"];
			  }else if(cellvalue=="saveChange"){
				  return "<span style='color:#ff0000'>[System]</span>&nbsp;"+i18n["lable_When_the_change_is_triggered_new"];
			  }else if(cellvalue=="requestProce"){
				  return i18n["lable_Request_process_flow_trigger"];
			  }else if(cellvalue=="changeProce"){
				  return i18n["lable_Circulation_trigger_change_process"];
			  }
		},
		/**
		 * @description 加载规则列表.
		 */
		showRulesGrid : function() {
			var _postData={};
			if(_flag=="changeProce" || _flag=="changeApproval"){//全文检索
				$.extend(_postData,{'rulePackageDto.module':'change'});
			}else{
				$.extend(_postData,{'rulePackageDto.module':'request'});
			}
			var params = $.extend({}, jqGridParams, {
				url : 'rulePackage!findRulePackageByPage.action',
				postData:_postData,
				colNames : [ 'ID', i18n['lable_created_drl_processing'], i18n['type'],'',
						i18n['lable_Rules_package_Remarks'], i18n['check'] ],
				colModel : [ {
					name : 'rulePackageNo',
					align : 'center',
					width : 20
				}, {
					name : 'packageName',
					align : 'center',
					width : 50,
					formatter : function(cellvalue, options, rowObject) {
						return cellvalue.replace("com.drools.drl.", "");
					}
				},
				{name:'flagName',align:'center',width:80,formatter:wstuo.rules.addRule.isToFlagName},
				{name:'flagName',align:'center',width:80},
				{
					name : 'rulePackageRemarks',
					align : 'center',
					width : 70
				}, {
					name : 'act',
					width : 25,
					align : 'center',
					sortable : false,
					formatter : wstuo.rules.addRule.confirmCheckFormatter
				} ],
				jsonReader : $.extend(jqGridJsonReader, {
					id : "rulePackageNo"
				}),
				sortname : 'rulePackageNo',
				pager : '#matchRuleSelectgridPager',
				multiselect : false,
				ondblClickRow:function(rowId){
					var data=$('#matchRuleSelectgrid').getRowData(rowId);
					wstuo.rules.addRule.confirmCheck(data.rulePackageNo,data.flagName,data.packageName.replace("com.drools.drl.", ""));
				},
				toolbar : true
			});
			$("#matchRuleSelectgrid").jqGrid(params);
			$("#matchRuleSelectgrid").navGrid('#matchRuleSelectgridPager',navGridParams);
		},

		/**
		 * @description 初始化
		 */
		init:function() {

			$("#addRule_loading").hide();
			$("#addRule_content").show();

			$('#addRule_team').change(function() {

				wstuo.rules.addRule.setPVHTML();
				wstuo.rules.addRule.setTerm();

			});

			$('#addRule_executeAction').change(function() {
				wstuo.rules.addRule.addRule_setExHTML();
			});
			
			// 请求规则
			if (_flag == "requestFit" || _flag == "requestProce") {
				$('#givenValue_Panel').click(wstuo.rules.addRule.addRule_selectServiceOrg);
			}

			$('#Proce_rulePackageName').click(function() {
				windows('selectRuleMatchRuleSelectWin', {width : 630});
				if(loadshowRulesGrid==false){
					loadshowRulesGrid=true;
					wstuo.rules.addRule.showRulesGrid();// 加载规则列表
				}else{
					$('#matchRuleSelectgrid').trigger('reloadGrid',[{"page":"1"}]);
				}
			});
			$('#addRule_addRulesToList').click(wstuo.rules.addRule.addToRuleList);
			$('#addRule_addActionToList').click(function() {
				if(($('#Proce_rulePackageNo').val()!='' && $('#Proce_rulePackageNo').val()!=null) || (_flag =='mailToRequest')){
					wstuo.rules.addRule.addToActionList();
				}else{
					msgAlert(i18n.rule_requestProcess_package_tip, 'info');
				}
			});
			$('#addRule_saveRuleBtn').click(wstuo.rules.addRule.saveRule);
			$('#addRule_returnRuleGrid').click(function() {
				
				basics.index.initContent('../pages/wstuo/rules/ruleMain.jsp?rulePackageNo='+_rulePackageNo+'&flag='+_flag);
				
			});
			// 初始化
			wstuo.rules.ruleCM.loadType(_flag);
			wstuo.rules.addRule.ruleTermSet();
			if(_flag =='mailToRequest'){
				wstuo.rules.ruleCM.loadType(_flag);
				wstuo.rules.addRule.executeAction();
			}else{
				$('#addRule_executeAction').html('<option value="">'+i18n["rule_requestProcess_package_tip"]+'</option>');
			}
			
			$('#multiterm_saveRuleBtn').click(
					wstuo.rules.addRule.addMultitermRule);
			for ( var i = 0; i <= 99; i++) {
				if (i == 50)
					$('#ruleSalience').append(
							"<option value='" + i + "' selected='selected'>"
									+ i + "</option>");
				else
					$('#ruleSalience').append(
							"<option value='" + i + "'>" + i + "</option>");
			}

		}
	};

}();
$(document).ready(wstuo.rules.addRule.init);
